package com.example.day16_mp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtils {
    private HttpUtils(){}
    private static HttpUtils httpUtils = null;
    public static HttpUtils getInstance(){
        if(httpUtils==null){
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    public String doget(String url){
        InputStream is = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestMethod("GET");
            connection.connect();
            if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder stringBuilder = new StringBuilder();
                String str = "";
                while ((str= reader.readLine())!=null){
                    stringBuilder.append(str);
                }
                return stringBuilder.toString();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
